#region

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.Reporting.WinForms;

#endregion

namespace Libraries
{
    public class ReportHelper
    {
        //const string REPORT_DEFINITION_NS = "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition/";
        //const string REPORT_DESIGNER_NS = "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner";

        public static void BindingDataToReport(ReportViewer reportViewControl, string fileReport,
                                               Dictionary<string, Object> datasource)
        {
            reportViewControl.ProcessingMode = ProcessingMode.Local;

            using (var readStream = new FileStream(fileReport, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                reportViewControl.LocalReport.LoadReportDefinition(readStream);
            }

            foreach (var dataSourceName in
                reportViewControl.LocalReport.GetDataSourceNames().Where(datasource.ContainsKey))
            {
                reportViewControl.LocalReport.DataSources.Add(
                    new ReportDataSource(dataSourceName, datasource[dataSourceName]));
            }

            reportViewControl.RefreshReport();
        }


        public static string ExportToPdf(ReportViewer reportViewer, string outputPdfPath = "", string reportName = "")
        {
            var pdfBytesData = reportViewer.LocalReport.Render("PDF");
            var pdfName = (string.IsNullOrEmpty(reportName) ? Path.GetRandomFileName() : reportName) + ".pdf";

            var tmpPdfFile = !string.IsNullOrEmpty(outputPdfPath)
                                 ? Path.Combine(outputPdfPath, pdfName)
                                 : Path.Combine(Path.GetTempPath(), pdfName);

            var pdfFileStream = File.Create(tmpPdfFile);

            pdfFileStream.Write(pdfBytesData, 0, pdfBytesData.Length);
            pdfFileStream.Close();

            return tmpPdfFile;
        }

       
    }
}